package main

import (
	"fmt"
	"math"
	"sort"
)

func main() {
	nums := []int{0, 1, 2}
	fmt.Println(threeSumClosest(nums, 0))
}

func threeSumClosest(nums []int, target int) int {
	length := len(nums)
	result := nums[0] + nums[1] + nums[length-1]
	sort.Ints(nums)
	for i := 0; i < length-2; i++ {
		lo := i + 1
		high := length - 1
		for lo < high {
			sum := nums[i] + nums[lo] + nums[high]
			if sum > target {
				high--
			} else {
				lo++
			}
			if math.Abs(float64(sum-target)) < math.Abs(float64(result-target)) {
				result = sum
			}
		}
	}
	return result
}
